package com.zj.fx.service.month;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zj.fx.common.base.BaseService;
import com.zj.fx.common.support.ConvertUtil;
import com.zj.fx.mapper.info.InfoWeightMapper;
import com.zj.fx.mapper.month.MonthSupplytaskDtlMapper;
import com.zj.fx.model.custom.Tablepar;
import com.zj.fx.model.info.*;
import com.zj.fx.model.month.*;
import com.zj.fx.shiro.util.ShiroUtils;
import com.zj.fx.util.SnowflakeIdWorker;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 月度供电所填报任务填报明细 MonthSupplytaskDtlService
 *
 * @author SQL_自动生成
 * @Title: MonthSupplytaskDtlService.java 
 * @Package com.zj.fx.service 
 * @email ${email}
 * @date 2023-06-09 17:15:40  
 **/
@Service
public class MonthSupplytaskDtlService implements BaseService<MonthSupplytaskDtl, MonthSupplytaskDtlExample> {
    @Autowired
    private MonthSupplytaskDtlMapper monthSupplytaskDtlMapper;
    @Autowired
    private InfoWeightMapper infoWeightMapper;


    /**
     * 分页查询
     *
     * @param
     * @param
     * @return
     */
    public PageInfo<MonthSupplytaskDtl> list(Tablepar tablepar, MonthSupplytaskDtl monthSupplytaskDtl) {
        MonthSupplytaskDtlExample testExample = new MonthSupplytaskDtlExample();
        //搜索
        if (StrUtil.isNotEmpty(tablepar.getSearchText())) {//小窗体
            testExample.createCriteria().andLikeQuery2(tablepar.getSearchText());
        } else {//大搜索
            testExample.createCriteria().andLikeQuery(monthSupplytaskDtl);
        }
        //表格排序
        //if(StrUtil.isNotEmpty(tablepar.getOrderByColumn())) {
        //	testExample.setOrderByClause(StringUtils.toUnderScoreCase(tablepar.getOrderByColumn()) +" "+tablepar.getIsAsc());
        //}else{
        //	testExample.setOrderByClause("id ASC");
        //}
        PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
        List<MonthSupplytaskDtl> list = monthSupplytaskDtlMapper.selectByExample(testExample);
        PageInfo<MonthSupplytaskDtl> pageInfo = new PageInfo<MonthSupplytaskDtl>(list);
        return pageInfo;
    }

    @Override
    public int deleteByPrimaryKey(String ids) {

        List<String> lista = ConvertUtil.toListStrArray(ids);
        MonthSupplytaskDtlExample example = new MonthSupplytaskDtlExample();
        example.createCriteria().andIdIn(lista);
        return monthSupplytaskDtlMapper.deleteByExample(example);


    }


    @Override
    public MonthSupplytaskDtl selectByPrimaryKey(String id) {

        return monthSupplytaskDtlMapper.selectByPrimaryKey(id);

    }


    @Override
    public int updateByPrimaryKeySelective(MonthSupplytaskDtl record) {
        return monthSupplytaskDtlMapper.updateByPrimaryKeySelective(record);
    }


    /**
     * 添加
     */
    @Override
    public int insertSelective(MonthSupplytaskDtl record) {

        //添加雪花主键id
        record.setId(SnowflakeIdWorker.getUUID());


        return monthSupplytaskDtlMapper.insertSelective(record);
    }


    @Override
    public int updateByExampleSelective(MonthSupplytaskDtl record, MonthSupplytaskDtlExample example) {

        return monthSupplytaskDtlMapper.updateByExampleSelective(record, example);
    }


    @Override
    public int updateByExample(MonthSupplytaskDtl record, MonthSupplytaskDtlExample example) {

        return monthSupplytaskDtlMapper.updateByExample(record, example);
    }

    @Override
    public List<MonthSupplytaskDtl> selectByExample(MonthSupplytaskDtlExample example) {

        return monthSupplytaskDtlMapper.selectByExample(example);
    }


    @Override
    public long countByExample(MonthSupplytaskDtlExample example) {

        return monthSupplytaskDtlMapper.countByExample(example);
    }


    @Override
    public int deleteByExample(MonthSupplytaskDtlExample example) {

        return monthSupplytaskDtlMapper.deleteByExample(example);
    }


    public List<MonthSupplytaskDtl> list2(MonthSupplytaskDtl monthSupplytaskDtl) {
        List<MonthSupplytaskDtl> list = monthSupplytaskDtlMapper.findupGrade(monthSupplytaskDtl);
        return list;
    }

    /*
        生成月度评价任务时，生成5级任务明细
     */
    public Integer generategrade5(InfoSupply infoSupply, MonthSupplytask monthSupplytask, InfoTarget infoTarget) {
        MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
        monthSupplytaskDtl.setId(SnowflakeIdWorker.getUUID());
        monthSupplytaskDtl.setFkTaskId(monthSupplytask.getId());
        monthSupplytaskDtl.setNum(infoTarget.getNum());
        monthSupplytaskDtl.setName(infoTarget.getName());
        monthSupplytaskDtl.setTargetScore(infoTarget.getTargetScore());
        monthSupplytaskDtl.setMeasuringUnit(infoTarget.getMeasuringUnit());
        monthSupplytaskDtl.setCountAmount(infoTarget.getCountAmount());
        monthSupplytaskDtl.setCountRegulation(infoTarget.getCountRegulation());
        monthSupplytaskDtl.setEvaluationPeriod(infoTarget.getEvaluationPeriod());
        monthSupplytaskDtl.setDeptId(infoTarget.getDeptId());
        monthSupplytaskDtl.setDeptName(infoTarget.getDeptName());
        monthSupplytaskDtl.setTactics(infoTarget.getTactics());
        monthSupplytaskDtl.setFkParentProjectId(infoTarget.getFkParentProjectId());
        //20230628 增加生成任务时写入tab
        String[] split = infoTarget.getNum().split("\\.");
        monthSupplytaskDtl.setTab(split[0]);

        //------------------设置是否手动填写逻辑-----------------------START

        //判断任务是否参与评价,不参与直接给满分，赋默认值
        if (MonthConstant.NOT.equals(infoTarget.getTypeNofill())){
            setDefault(infoTarget, monthSupplytaskDtl);
        } else {

            if (infoTarget.getFkParentProjectId().equals("4.1.1.1") && Strings.isBlank(infoSupply.getPartyBranch())){
                monthSupplytaskDtl.setIsauto(MonthConstant.IS_INT);
                if (infoTarget.getTactics().equals(MonthConstant.DTL_TACTIC_ISORNOT)) {
                    if (infoTarget.getTypeOption() == MonthConstant.NOT_INT) {
                        monthSupplytaskDtl.setSelfValue(MonthConstant.NOT);
                    } else if (infoTarget.getTypeOption() == MonthConstant.IS_INT) {
                        monthSupplytaskDtl.setSelfValue(MonthConstant.IS);
                    }
                } else {
                    monthSupplytaskDtl.setSelfValue(MonthConstant.AUTO_GENERATE);
                }
                monthSupplytaskDtl.setSelfScore("25");

            } else {
                //根据评价周期及任务属性（是否包含高危、是否10kv、是否新兴）判定是否手动填写
                String evaluationPeriod = infoTarget.getEvaluationPeriod();
                String yearandMonth = monthSupplytask.getTaskMonth();
                String[] yearandMonths = yearandMonth.split("-");
                Integer year = Integer.parseInt(yearandMonths[0]);
                Integer month = Integer.parseInt(yearandMonths[1]);

                //查询供电所三大属性
                Integer supplytypeImportant = infoSupply.getTypeImportant();
                Integer supplytype10kv = infoSupply.getType10kv();
                Integer supplytypeRising = infoSupply.getTypeRising();
                //新增八大属性查询
                String supplytypeJkxl = infoSupply.getTypeJkxl();
                String supplytypeZssb = infoSupply.getTypeZssb();
                String supplytypeDldl = infoSupply.getTypeDldl();
                String supplytypeZykgz = infoSupply.getTypeZykgz();
                String supplytypeHwdy = infoSupply.getTypeHwdy();
                String supplytypePds = infoSupply.getTypePds();
                String supplytypeXsbdz = infoSupply.getTypeXsbdz();
                String supplytypeDlxltd = infoSupply.getTypeDlxltd();

                //查询项目提升指标中是否参与评价
                Integer typeImportant = infoTarget.getTypeImportant();
                Integer type10kv = infoTarget.getType10kv();
                Integer typeRising = infoTarget.getTypeRising();
                //新增八大属性查询
                String typeJkxl = infoTarget.getTypeJkxl();
                String typeZssb = infoTarget.getTypeZssb();
                String typeDldl = infoTarget.getTypeDldl();
                String typeZykgz = infoTarget.getTypeZykgz();
                String typeHwdy = infoTarget.getTypeHwdy();
                String typePds = infoTarget.getTypePds();
                String typeXsbdz = infoTarget.getTypeXsbdz();
                String typeDlxltd = infoTarget.getTypeDlxltd();


                //以10kv为例，该供电所没有10kv业务，但是该项是10kv评价项，该项给满分，其余同理
                if ((supplytypeImportant == MonthConstant.NOT_INT && typeImportant == MonthConstant.IS_INT)
                        || (supplytype10kv == MonthConstant.NOT_INT && type10kv == MonthConstant.IS_INT)
                        || (supplytypeRising == MonthConstant.NOT_INT && typeRising == MonthConstant.IS_INT)
                        || (MonthConstant.NOT.equals(supplytypeJkxl) && MonthConstant.IS.equals(typeJkxl))
                        || (MonthConstant.NOT.equals(supplytypeZssb) && MonthConstant.IS.equals(typeZssb))
                        || (MonthConstant.NOT.equals(supplytypeDldl) && MonthConstant.IS.equals(typeDldl))
                        || (MonthConstant.NOT.equals(supplytypeZykgz) && MonthConstant.IS.equals(typeZykgz))
                        || (MonthConstant.NOT.equals(supplytypeHwdy) && MonthConstant.IS.equals(typeHwdy))
                        || (MonthConstant.NOT.equals(supplytypePds) && MonthConstant.IS.equals(typePds))
                        || (MonthConstant.NOT.equals(supplytypeXsbdz) && MonthConstant.IS.equals(typeXsbdz))
                        || (MonthConstant.NOT.equals(supplytypeDlxltd) && MonthConstant.IS.equals(typeDlxltd))) {
                    setDefault(infoTarget, monthSupplytaskDtl);
                } else {
                    //评价周期（0月度/1季度/2半年/3年初/4年末）
                    if (evaluationPeriod.equals("1")) {//季度
                        if (month % 3 == 0) {
                            //3\6\9\12 季度最后一个月需要手动填写
                            monthSupplytaskDtl.setIsauto(MonthConstant.NOT_INT);
                        } else {
                            setDefault(infoTarget, monthSupplytaskDtl);
                        }
                    } else if (evaluationPeriod.equals("2")) {//半年
                        if (month % 6 == 0) {
                            //6\12 半年度最后一个月需要手动填写
                            monthSupplytaskDtl.setIsauto(MonthConstant.NOT_INT);
                        } else {
                            setDefault(infoTarget, monthSupplytaskDtl);
                        }
                    } else if (evaluationPeriod.equals("3")) {//年初
                        if (month == 1) {
                            //1月 需要手动填写
                            monthSupplytaskDtl.setIsauto(MonthConstant.NOT_INT);
                        } else {
                            //20230628 逻辑2 只查询上个月对应的五级项目，扣分项是否为0（self_score）,后期加完生成任务限制后，应查询的是审核后的结果
                            String lastMonth = null;
                            if (month - 1 < 10) {
                                lastMonth = "0" + (month - 1);
                            } else {
                                lastMonth = "" + (month - 1);
                            }
                            String lastYearandMonth = year + "-" + lastMonth;
                            MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
                            MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
                            criteria.andTaskMonthEqualTo(lastYearandMonth);
                            criteria.andFkSupplyIdEqualTo(infoSupply.getId());
                            criteria.andNumEqualTo(infoTarget.getNum());
                            //criteria.andTaskStateEqualTo(MonthConstant.DTL_STATE_ISFINISHED);//后期优化
                            List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
                            if (monthSupplytaskDtls!=null && monthSupplytaskDtls.size()==1){
                                MonthSupplytaskDtl monthSupplytaskDtl1 = monthSupplytaskDtls.get(0);
                                if (Strings.isNotBlank(monthSupplytaskDtl1.getSelfScore()) && BigDecimal.ZERO.compareTo(new BigDecimal(monthSupplytaskDtl1.getSelfScore()))==0){//后期加完生成任务限制后，应查询的是审核后的结果
                                    setDefault(infoTarget, monthSupplytaskDtl);
                                } else {
                                    monthSupplytaskDtl.setIsauto(MonthConstant.NOT_INT);
                                }
                            }else {
                                monthSupplytaskDtl.setIsauto(MonthConstant.NOT_INT);
                            }

                        }
                    } else if (evaluationPeriod.equals("4")) {//年末
                        if (month == 12) {
                            //12 年度最后一个月需要手动填写
                            monthSupplytaskDtl.setIsauto(MonthConstant.NOT_INT);
                        } else {
                            setDefault(infoTarget, monthSupplytaskDtl);
                        }
                    } else {
                        monthSupplytaskDtl.setIsauto(MonthConstant.NOT_INT);
                    }
                }
            }
        }

        //------------------设置是否手动填写逻辑-----------------------END

        monthSupplytaskDtl.setProGrade(MonthConstant.DTL_PROGRADE_FIVE);
        monthSupplytaskDtl.setFkSupplyId(infoSupply.getId());
        monthSupplytaskDtl.setSupplyName(infoSupply.getName());
        monthSupplytaskDtl.setTaskMonth(monthSupplytask.getTaskMonth());
        monthSupplytaskDtl.setTypeOption(infoTarget.getTypeOption());
        monthSupplytaskDtl.setTaskState(MonthConstant.DTL_STATE_NOFILL);
        return monthSupplytaskDtlMapper.insertSelective(monthSupplytaskDtl);
    }

    /**
     * 生成任务明细默认填写项
     *
     * @param infoTarget
     * @param monthSupplytaskDtl
     */
    private void setDefault(InfoTarget infoTarget, MonthSupplytaskDtl monthSupplytaskDtl) {
        monthSupplytaskDtl.setIsauto(MonthConstant.IS_INT);
        if (infoTarget.getTactics().equals(MonthConstant.DTL_TACTIC_ISORNOT)) {
            //如果策略为是否，并且否为扣分项，就将默认值设置为是，反之同理
            if (infoTarget.getTypeOption() == MonthConstant.NOT_INT) {
                monthSupplytaskDtl.setSelfValue("1");
            } else if (infoTarget.getTypeOption() == MonthConstant.IS_INT) {
                monthSupplytaskDtl.setSelfValue("0");
            }
        } else {
            monthSupplytaskDtl.setSelfValue(MonthConstant.AUTO_GENERATE);
        }
        monthSupplytaskDtl.setSelfScore(MonthConstant.SCORE_ZERO_STR);

    }

    /*
       生成月度评价任务时，生成4级任务明细
    */
    public Integer generategrade4(InfoSupply infoSupply, MonthSupplytask monthSupplytask, InfoProject infoProject) {
        MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
        monthSupplytaskDtl.setId(SnowflakeIdWorker.getUUID());
        monthSupplytaskDtl.setFkTaskId(monthSupplytask.getId());
        monthSupplytaskDtl.setNum(infoProject.getNum());
        monthSupplytaskDtl.setName(infoProject.getContent());
        monthSupplytaskDtl.setFkParentProjectId(infoProject.getParentNum());
        monthSupplytaskDtl.setFkSupplyId(infoSupply.getId());
        monthSupplytaskDtl.setSupplyName(infoSupply.getName());
        monthSupplytaskDtl.setProGrade(MonthConstant.DTL_PROGRADE_FOUR);
        monthSupplytaskDtl.setFullMark(infoProject.getScore());
        monthSupplytaskDtl.setTaskState(MonthConstant.DTL_STATE_NOFILL);
        monthSupplytaskDtl.setTaskMonth(monthSupplytask.getTaskMonth());
        //20230628 增加生成任务时写入tab
        String[] split = infoProject.getNum().split("\\.");
        monthSupplytaskDtl.setTab(split[0]);
        return monthSupplytaskDtlMapper.insertSelective(monthSupplytaskDtl);
    }

    /**
     * 查询五级项目总扣分为0的四级项目id（没填写为空的记作1分，代表有扣分，先不合算总分）
     *
     * @param monthSupplytask
     * @return
     */
    public List<MonthSupplytaskDtl> findFullMark(MonthSupplytask monthSupplytask) {
        MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
        monthSupplytaskDtl.setFkTaskId(monthSupplytask.getId());
        return monthSupplytaskDtlMapper.findFullMark(monthSupplytaskDtl);
    }

    /**
     * 填报时更新
     *
     * @param monthSupplytaskDtl
     * @return
     */
    public MonthSupplytaskDtl updateSelf(MonthSupplytaskDtl monthSupplytaskDtl) {
        //----------------0、原始数据获取
        String id = monthSupplytaskDtl.getId();
        String typeValue = monthSupplytaskDtl.getSelfValue();//几处
        //----------------1、查询当前5级项目信息
        monthSupplytaskDtl = monthSupplytaskDtlMapper.selectByPrimaryKey(id);
        String parentId = monthSupplytaskDtl.getFkParentProjectId();
        String countAmount = monthSupplytaskDtl.getCountAmount();//加分扣分
        String countRegulation = monthSupplytaskDtl.getCountRegulation();//系数

        //-------------------2、查询当前5级项目对应四级项目信息，获取关键数值
        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
        criteria.andNumEqualTo(parentId);
        criteria.andFkTaskIdEqualTo(monthSupplytaskDtl.getFkTaskId());
        List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
        MonthSupplytaskDtl monthSupplytaskDtl4 = monthSupplytaskDtls.get(0);
        String fullMark = monthSupplytaskDtl4.getFullMark();//满分
        String maxdeduction = monthSupplytaskDtl4.getFullMark();//最多扣分------坑----最多扣分和满分是否相同，不相同要加字段

        //如果填报值为空并传到后端，说明之前完成了填写并完成了计算，此时应该找到该条记录，将填写值和扣分值置为null，对应四级得分置为null
        if (Strings.isNotBlank(typeValue)) {
            //------------------3、计算当前5级项目的扣分。更新当前五级项目
            //评分策略（1输入量值（目标）/2是否/3输入量值）
            BigDecimal totalSub = BigDecimal.ZERO;
            if (monthSupplytaskDtl.getTactics().equals("1")) {
                //目标值
                BigDecimal targetScore = new BigDecimal(monthSupplytaskDtl.getTargetScore());
                BigDecimal typeValuebigDec = new BigDecimal(typeValue);
                BigDecimal countAmountDec = new BigDecimal(countAmount);
                BigDecimal countRegulationDec = new BigDecimal(countRegulation);
                //判断加减分，如果是加分，逻辑为大于目标值则按规则扣分
                if (countAmountDec.compareTo(BigDecimal.ZERO) > 0) {
                    if (typeValuebigDec.compareTo(targetScore) > 0) {
                        BigDecimal cha = typeValuebigDec.subtract(targetScore);
                        BigDecimal count = cha.divide(countAmountDec, 0, RoundingMode.DOWN);
                        totalSub = count.multiply(countRegulationDec);
                    }
                } else {
                    if (typeValuebigDec.compareTo(targetScore) < 0) {
                        BigDecimal cha = targetScore.subtract(typeValuebigDec);
                        BigDecimal count = cha.divide(countAmountDec.abs(), 0, RoundingMode.DOWN);
                        totalSub = count.multiply(countRegulationDec);
                    }
                }
            } else if (monthSupplytaskDtl.getTactics().equals("2")) {
                //如果扣分项与当前项一致，开始计算扣分分数
                if (monthSupplytaskDtl.getTypeOption().toString().equals(typeValue)) {
                    //扣分
                    BigDecimal multiply = new BigDecimal(countAmount).multiply(new BigDecimal(countRegulation)).abs();
                    //实际扣分--对比最大扣分上限值
                    if (multiply.compareTo(new BigDecimal(maxdeduction)) > 0) {
                        totalSub = new BigDecimal(maxdeduction);
                    } else {
                        totalSub = multiply;
                    }
                }

            } else if (monthSupplytaskDtl.getTactics().equals("3")) {
                //当前都按照扣分来计算 取绝对值
                //扣分
                BigDecimal multiply = new BigDecimal(countAmount).multiply(new BigDecimal(countRegulation)).multiply(new BigDecimal(typeValue)).abs();
                //实际扣分--对比最大扣分上限值
                if (multiply.compareTo(new BigDecimal(maxdeduction)) > 0) {
                    totalSub = new BigDecimal(maxdeduction);
                } else {
                    totalSub = multiply;
                }
            }
            monthSupplytaskDtl.setSelfScore(totalSub.toString());
        } else {
            typeValue = "";
            monthSupplytaskDtl.setSelfScore("");
        }

        //更新5级项目自评价得分，用于前端表格展示
        monthSupplytaskDtl.setSelfValue(typeValue);
        monthSupplytaskDtlMapper.updateByPrimaryKeySelective(monthSupplytaskDtl);

        BigDecimal pro4Score = new BigDecimal(fullMark);
        //四级项目下有多条五级项目的。每次循环计算分数
        MonthSupplytaskDtl monthSupplytaskDtl1 = new MonthSupplytaskDtl();
        monthSupplytaskDtl1.setFkTaskId(monthSupplytaskDtl.getFkTaskId());
        monthSupplytaskDtl1.setFkParentProjectId(monthSupplytaskDtl.getFkParentProjectId());
        //查询出司机项目下对应的所有五级项目
        BigDecimal grade5TotalScore = BigDecimal.ZERO;
        List<MonthSupplytaskDtl> monthSupplytaskDtls1 = this.findgrade5by4(monthSupplytaskDtl1);
        List<MonthSupplytaskDtl> collect = monthSupplytaskDtls1.stream().filter(s -> Strings.isNotBlank(s.getSelfValue())).collect(Collectors.toList());
        if (collect.size() == monthSupplytaskDtls1.size()) {
            grade5TotalScore = monthSupplytaskDtls1.stream().map(MonthSupplytaskDtl::getSelfScore).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (grade5TotalScore.compareTo(new BigDecimal(maxdeduction)) > 0) {
                pro4Score = pro4Score.subtract(new BigDecimal(maxdeduction)).setScale(2);//四舍五入保留两位小数
            } else {
                pro4Score = pro4Score.subtract(grade5TotalScore).setScale(2);
            }
        } else {
            pro4Score = null;
        }


        //更新4级项目自评价得分，用于后端统计计算
        if (typeValue == "") {
            monthSupplytaskDtl4.setSelfScore("");
        } else {
            if (pro4Score == null) {
                monthSupplytaskDtl4.setSelfScore("");
            } else {
                monthSupplytaskDtl4.setSelfScore(pro4Score.toString());
            }
        }
        return monthSupplytaskDtl4;
    }


    public List<MonthSupplytaskDtl> findgrade5by4(MonthSupplytaskDtl monthSupplytaskDtl1) {
        return monthSupplytaskDtlMapper.findgrade5by4(monthSupplytaskDtl1);
    }

    /**
     * 根据月度评价任务id查看对应填报任务明细是否填报完整
     *
     * @param monthSupplytask
     * @return
     */
    public Boolean checkCanCommit(MonthSupplytask monthSupplytask) {
        //查询四级项目总分及各四级项目实际得分总和
        MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
        monthSupplytaskDtl.setFkTaskId(monthSupplytask.getId());
        MonthSupplytaskDtl monthSupplytaskDtl1 = monthSupplytaskDtlMapper.findgrade4Score(monthSupplytaskDtl);
        String sumFullMark = monthSupplytaskDtl1.getSumFullMark();
        String sumSelfScore = monthSupplytaskDtl1.getSumSelfScore();
        MonthSupplytaskDtl monthSupplytaskDtl2 = monthSupplytaskDtlMapper.findgrade5Score(monthSupplytaskDtl);
        String sumDeduct = monthSupplytaskDtl2.getSumDeduct();
        if (new BigDecimal(sumSelfScore).add(new BigDecimal(sumDeduct)).compareTo(new BigDecimal(sumFullMark)) == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据月度评价任务id查看对应填报任务明细是否有空白项未填
     *
     * @param monthSupplytask
     * @return
     */
    public List<MonthSupplytaskDtl> checkAllFill(MonthSupplytask monthSupplytask) {
        MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
        monthSupplytaskDtl.setFkTaskId(monthSupplytask.getId());
        monthSupplytaskDtl.setProGrade(MonthConstant.DTL_PROGRADE_FIVE);
//        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
//        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
//        criteria.andFkTaskIdEqualTo(monthSupplytask.getId());
//        criteria.andProGradeEqualTo(MonthConstant.DTL_PROGRADE_FIVE);
//        criteria.and
        return monthSupplytaskDtlMapper.checkAllFill(monthSupplytaskDtl);
    }

    /**
     * 根据页签、taskId、部门id、三级编码、查询三级项目下对应五级项目
     *
     * @param monthSupplytaskDtl
     * @return
     */
    public List<MonthSupplytaskDtl> findAuditTabbyThree(MonthSupplytaskDtl monthSupplytaskDtl) {
        List<MonthSupplytaskDtl> list = monthSupplytaskDtlMapper.list4audit(monthSupplytaskDtl);
        return list;
    }

    /**
     * 根据负责部门、任务id、任务状态查询5级项目
     *
     * @param monthSupplytask
     * @return
     */
    public List<MonthSupplytaskDtl> findbyDepandTaskidandState(MonthSupplytask monthSupplytask) {
        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
        criteria.andFkTaskIdEqualTo(monthSupplytask.getId());
        criteria.andProGradeEqualTo(MonthConstant.DTL_PROGRADE_FIVE);
        criteria.andDeptIdEqualTo(ShiroUtils.getDepId());
        criteria.andTaskStateEqualTo(monthSupplytask.getTaskState());
        return monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
    }

    /**
     * 根据负责部门、任务id、任务级别、父级num查询
     *
     * @param monthSupplytaskDtl
     * @return
     */
    public List<MonthSupplytaskDtl> findbyDepandTaskidandGrade(MonthSupplytaskDtl monthSupplytaskDtl) {
        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
        criteria.andFkTaskIdEqualTo(monthSupplytaskDtl.getFkTaskId());
        criteria.andProGradeEqualTo(monthSupplytaskDtl.getProGrade());
        criteria.andFkParentProjectIdEqualTo(monthSupplytaskDtl.getFkParentProjectId());
        if (MonthConstant.DTL_PROGRADE_FIVE.equals(monthSupplytaskDtl.getProGrade())) {
            criteria.andDeptIdEqualTo(ShiroUtils.getDepId());
        }
        return monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
    }

    /**
     * 根据任务id、任务级别查询
     *
     * @param monthSupplytaskDtl
     * @return
     */
    public List<MonthSupplytaskDtl> findbyTaskIdandGrade(MonthSupplytaskDtl monthSupplytaskDtl) {
        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
        criteria.andFkTaskIdEqualTo(monthSupplytaskDtl.getFkTaskId());
        criteria.andProGradeEqualTo(monthSupplytaskDtl.getProGrade());
        return monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
    }

    /**
     * 查询部门负责的对应四级项目明细编号
     *
     * @param monthSupplytaskDtl
     * @return
     */
    public List<String> findDistinctNum4byDep(MonthSupplytaskDtl monthSupplytaskDtl) {
        List<String> list = monthSupplytaskDtlMapper.findDistinctNum4byDep(monthSupplytaskDtl);
        return list;
    }

    /**
     * 根据任务id、任务编码、任务等级查询任务明细
     *
     * @param monthSupplytaskDtl
     * @return
     */
    public List<MonthSupplytaskDtl> findbyTaskIdandNum(MonthSupplytaskDtl monthSupplytaskDtl) {
        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
        criteria.andFkTaskIdEqualTo(monthSupplytaskDtl.getFkTaskId());
        criteria.andProGradeEqualTo(monthSupplytaskDtl.getProGrade());
        criteria.andNumEqualTo(monthSupplytaskDtl.getNum());
        return monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
    }

    /**
     * 查询评价指标中不同的部门list
     * @param monthSupplytaskDtl
     * @return
     */
    public List<MonthSupplytaskDtl> findDistinctDept(MonthSupplytaskDtl monthSupplytaskDtl) {
        return monthSupplytaskDtlMapper.findDistinctDept(monthSupplytaskDtl);
    }

    /**
     * 查询系统部门列表相关，是否有指标审核状态
     * @param monthSupplytaskDtl
     * @return
     */
    public List<MonthSupplytaskDtl> findDistinctDeptAll(MonthSupplytaskDtl monthSupplytaskDtl) {
        return monthSupplytaskDtlMapper.findDistinctDeptAll(monthSupplytaskDtl);
    }

    public List<MonthSupplytaskDtl> getScoreGroupbyTabbyDep(MonthSupplytaskDtl monthSupplytaskDtl) {
        return monthSupplytaskDtlMapper.getScoreGroupbyTabbyDep(monthSupplytaskDtl);
    }

    public String findFullMarkbyFktaskid(String fktaskid) {
        return monthSupplytaskDtlMapper.findFullMarkbyFktaskid(fktaskid);
    }

    public List<MonthSupplytaskDtl> findFinishMark(MonthSupplytask monthSupplytask) {
        MonthSupplytaskDtl monthSupplytaskDtl = new MonthSupplytaskDtl();
        monthSupplytaskDtl.setFkTaskId(monthSupplytask.getId());
        return monthSupplytaskDtlMapper.findFinishMark(monthSupplytaskDtl);
    }

    public List<MonthSupplytaskDtl> list4subaudit(MonthSupplytaskDtl monthSupplytaskDtl) {
        return monthSupplytaskDtlMapper.list4subaudit(monthSupplytaskDtl);
    }

    public String findSelfScoreTotal(MonthSupplytaskDtl monthSupplytaskDtl) {
        return monthSupplytaskDtlMapper.findSelfScoreTotal(monthSupplytaskDtl);
    }

    public MonthResult findSelfScoreGroupbyTab(MonthSupplytaskDtl monthSupplytaskDtl) {
        MonthResult monthResult = new MonthResult();
        List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlMapper.findSelfScoreGroupbyTab(monthSupplytaskDtl);

        //查询权重表对应各项目权重
        InfoWeightExample infoWeightExample = new InfoWeightExample();
        InfoWeightExample.Criteria criteria = infoWeightExample.createCriteria();
        criteria.andWeightIsNotNull();
        List<InfoWeight> infoWeights = infoWeightMapper.selectByExample(infoWeightExample);
        BigDecimal type1Weight = BigDecimal.ZERO;
        BigDecimal type2Weight = BigDecimal.ZERO;
        BigDecimal type3Weight = BigDecimal.ZERO;
        BigDecimal type4Weight = BigDecimal.ZERO;
        BigDecimal type5Weight = BigDecimal.ZERO;
        BigDecimal type6Weight = BigDecimal.ZERO;
        BigDecimal type7Weight = BigDecimal.ZERO;
        for (InfoWeight infoWeight : infoWeights) {
            if ("1".equals(infoWeight.getNum())){
                type1Weight = new BigDecimal(infoWeight.getWeight());
            } else if ("2".equals(infoWeight.getNum())){
                type2Weight = new BigDecimal(infoWeight.getWeight());
            } else if ("3".equals(infoWeight.getNum())){
                type3Weight = new BigDecimal(infoWeight.getWeight());
            } else if ("4".equals(infoWeight.getNum())){
                type4Weight = new BigDecimal(infoWeight.getWeight());
            } else if ("5".equals(infoWeight.getNum())){
                type5Weight = new BigDecimal(infoWeight.getWeight());
            } else if ("6".equals(infoWeight.getNum())){
                type6Weight = new BigDecimal(infoWeight.getWeight());
            } else if ("7".equals(infoWeight.getNum())){
                type7Weight = new BigDecimal(infoWeight.getWeight());
            }
        }
        
        BigDecimal totalScore = BigDecimal.ZERO;
        BigDecimal totalMark = BigDecimal.ZERO;
        for (MonthSupplytaskDtl supplytaskDtl : monthSupplytaskDtls) {
            if ("1".equals(supplytaskDtl.getTab())){
                monthResult.setYingxiaoScore(supplytaskDtl.getScore());
                totalScore = totalScore.add(new BigDecimal(supplytaskDtl.getScore()).multiply(type1Weight));
            } else if ("2".equals(supplytaskDtl.getTab())){
                monthResult.setYunjianScore(supplytaskDtl.getScore());
                totalScore = totalScore.add(new BigDecimal(supplytaskDtl.getScore()).multiply(type2Weight));
            } else if ("3".equals(supplytaskDtl.getTab())){
                monthResult.setAnquanScore(supplytaskDtl.getScore());
                totalScore = totalScore.add(new BigDecimal(supplytaskDtl.getScore()).multiply(type3Weight));
            } else if ("4".equals(supplytaskDtl.getTab())){
                monthResult.setDangjianScore(supplytaskDtl.getScore());
                totalScore = totalScore.add(new BigDecimal(supplytaskDtl.getScore()).multiply(type4Weight));
            } else if ("5".equals(supplytaskDtl.getTab())){
                monthResult.setShuzihuaScore(supplytaskDtl.getScore());
                totalScore = totalScore.add(new BigDecimal(supplytaskDtl.getScore()).multiply(type5Weight));
            } else if ("6".equals(supplytaskDtl.getTab())){
                monthResult.setFazhanScore(supplytaskDtl.getScore());
                totalScore = totalScore.add(new BigDecimal(supplytaskDtl.getScore()).multiply(type6Weight));
            } else if ("7".equals(supplytaskDtl.getTab())){
                monthResult.setWuxiaoScore(supplytaskDtl.getScore());
                totalScore = totalScore.add(new BigDecimal(supplytaskDtl.getScore()).multiply(type7Weight));
            }
            totalMark = totalMark.add(new BigDecimal(supplytaskDtl.getScore()));
        }
        monthResult.setTotalScore(totalScore.setScale(2));
        monthResult.setTotalMark(totalMark.setScale(2));
        return monthResult;
    }

    /**
     * @description: 供电所查看填报结果（带审核分数）
     * @author SQL
     * @date 2023/07/14 15:01
     * @version 1.0
     */
    public List<MonthSupplytaskDtl> list4SelfResult(MonthSupplytaskDtl monthSupplytaskDtl) {
        List<MonthSupplytaskDtl> list = monthSupplytaskDtlMapper.list4SelfResult(monthSupplytaskDtl);
        return list;
    }

    /**
     * @description: 根据taskid查看对应供电所填报的扣分项
     * @author SQL
     * @date 2023/07/19 14:31
     * @version 1.0
     */
    public PageInfo<MonthSupplytaskDtl> list4supplydeduction(String id,Tablepar tablepar) {
        PageHelper.startPage(tablepar.getPage(), tablepar.getLimit());
        List<MonthSupplytaskDtl> list = monthSupplytaskDtlMapper.list4supplydeduction(id);
        //对评价方式内容做去格式处理
        for (MonthSupplytaskDtl monthSupplytaskDtl : list) {
            //去除换行符，否则前端传递参数带换行符有问题，后期考虑前端优化
            String content = monthSupplytaskDtl.getContent();
            Pattern p = Pattern.compile("\\s*|\t|\r|\n"); // 去除多个空格，去除制表符，回车，换行
            Matcher m = p.matcher(content);
            content = m.replaceAll("");
            monthSupplytaskDtl.setContent(content);
        }
        PageInfo<MonthSupplytaskDtl> pageInfo = new PageInfo<MonthSupplytaskDtl>(list);
        return pageInfo;
    }

    /**
     * 生成任务时自动填写RPA抓取值
     *
     * @param monthSupplytaskDtl
     * @return
     */
    public MonthSupplytaskDtl updateSelf4Rpaauto(MonthSupplytaskDtl monthSupplytaskDtl) {
        //----------------0、原始数据获取
        String id = monthSupplytaskDtl.getId();
        String typeValue = monthSupplytaskDtl.getSelfValue();//几处
        //----------------1、查询当前5级项目信息
        monthSupplytaskDtl = monthSupplytaskDtlMapper.selectByPrimaryKey(id);
        String parentId = monthSupplytaskDtl.getFkParentProjectId();
        String countAmount = monthSupplytaskDtl.getCountAmount();//加分扣分
        String countRegulation = monthSupplytaskDtl.getCountRegulation();//系数

        //-------------------2、查询当前5级项目对应四级项目信息，获取关键数值
        MonthSupplytaskDtlExample monthSupplytaskDtlExample = new MonthSupplytaskDtlExample();
        MonthSupplytaskDtlExample.Criteria criteria = monthSupplytaskDtlExample.createCriteria();
        criteria.andNumEqualTo(parentId);
        criteria.andFkTaskIdEqualTo(monthSupplytaskDtl.getFkTaskId());
        List<MonthSupplytaskDtl> monthSupplytaskDtls = monthSupplytaskDtlMapper.selectByExample(monthSupplytaskDtlExample);
        MonthSupplytaskDtl monthSupplytaskDtl4 = monthSupplytaskDtls.get(0);
        String fullMark = monthSupplytaskDtl4.getFullMark();//满分
        String maxdeduction = monthSupplytaskDtl4.getFullMark();//最多扣分------坑----最多扣分和满分是否相同，不相同要加字段

        //如果填报值为空并传到后端，说明之前完成了填写并完成了计算，此时应该找到该条记录，将填写值和扣分值置为null，对应四级得分置为null
        if (Strings.isNotBlank(typeValue)) {
            //------------------3、计算当前5级项目的扣分。更新当前五级项目
            //评分策略（1输入量值（目标）/2是否/3输入量值）
            BigDecimal totalSub = BigDecimal.ZERO;
            if (monthSupplytaskDtl.getTactics().equals("1")) {
                //目标值
                BigDecimal targetScore = new BigDecimal(monthSupplytaskDtl.getTargetScore());
                BigDecimal typeValuebigDec = new BigDecimal(typeValue);
                BigDecimal countAmountDec = new BigDecimal(countAmount);
                BigDecimal countRegulationDec = new BigDecimal(countRegulation);
                //判断加减分，如果是加分，逻辑为大于目标值则按规则扣分
                if (countAmountDec.compareTo(BigDecimal.ZERO) > 0) {
                    if (typeValuebigDec.compareTo(targetScore) > 0) {
                        BigDecimal cha = typeValuebigDec.subtract(targetScore);
                        BigDecimal count = cha.divide(countAmountDec, 0, RoundingMode.DOWN);
                        totalSub = count.multiply(countRegulationDec);
                    }
                } else {
                    if (typeValuebigDec.compareTo(targetScore) < 0) {
                        BigDecimal cha = targetScore.subtract(typeValuebigDec);
                        BigDecimal count = cha.divide(countAmountDec.abs(), 0, RoundingMode.DOWN);
                        totalSub = count.multiply(countRegulationDec);
                    }
                }
            } else if (monthSupplytaskDtl.getTactics().equals("2")) {
                //如果扣分项与当前项一致，开始计算扣分分数
                if (monthSupplytaskDtl.getTypeOption().toString().equals(typeValue)) {
                    //扣分
                    BigDecimal multiply = new BigDecimal(countAmount).multiply(new BigDecimal(countRegulation)).abs();
                    //实际扣分--对比最大扣分上限值
                    if (multiply.compareTo(new BigDecimal(maxdeduction)) > 0) {
                        totalSub = new BigDecimal(maxdeduction);
                    } else {
                        totalSub = multiply;
                    }
                }

            } else if (monthSupplytaskDtl.getTactics().equals("3")) {
                //当前都按照扣分来计算 取绝对值
                //扣分
                BigDecimal multiply = new BigDecimal(countAmount).multiply(new BigDecimal(countRegulation)).multiply(new BigDecimal(typeValue)).abs();
                //实际扣分--对比最大扣分上限值
                if (multiply.compareTo(new BigDecimal(maxdeduction)) > 0) {
                    totalSub = new BigDecimal(maxdeduction);
                } else {
                    totalSub = multiply;
                }
            }
            monthSupplytaskDtl.setSelfScore(totalSub.toString());
        } else {
            typeValue = "";
            monthSupplytaskDtl.setSelfScore("");
        }

        //更新5级项目自评价得分，用于前端表格展示
        monthSupplytaskDtl.setSelfValue(typeValue);
        monthSupplytaskDtl.setIsauto(MonthConstant.IS_INT);
        monthSupplytaskDtlMapper.updateByPrimaryKeySelective(monthSupplytaskDtl);

        BigDecimal pro4Score = new BigDecimal(fullMark);
        //四级项目下有多条五级项目的。每次循环计算分数
        MonthSupplytaskDtl monthSupplytaskDtl1 = new MonthSupplytaskDtl();
        monthSupplytaskDtl1.setFkTaskId(monthSupplytaskDtl.getFkTaskId());
        monthSupplytaskDtl1.setFkParentProjectId(monthSupplytaskDtl.getFkParentProjectId());
        //查询出司机项目下对应的所有五级项目
        BigDecimal grade5TotalScore = BigDecimal.ZERO;
        List<MonthSupplytaskDtl> monthSupplytaskDtls1 = this.findgrade5by4(monthSupplytaskDtl1);
        List<MonthSupplytaskDtl> collect = monthSupplytaskDtls1.stream().filter(s -> Strings.isNotBlank(s.getSelfValue())).collect(Collectors.toList());
        if (collect.size() == monthSupplytaskDtls1.size()) {
            grade5TotalScore = monthSupplytaskDtls1.stream().map(MonthSupplytaskDtl::getSelfScore).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (grade5TotalScore.compareTo(new BigDecimal(maxdeduction)) > 0) {
                pro4Score = pro4Score.subtract(new BigDecimal(maxdeduction)).setScale(2);//四舍五入保留两位小数
            } else {
                pro4Score = pro4Score.subtract(grade5TotalScore).setScale(2);
            }
        } else {
            pro4Score = null;
        }


        //更新4级项目自评价得分，用于后端统计计算
        if (typeValue == "") {
            monthSupplytaskDtl4.setSelfScore("");
        } else {
            if (pro4Score == null) {
                monthSupplytaskDtl4.setSelfScore("");
            } else {
                monthSupplytaskDtl4.setSelfScore(pro4Score.toString());
            }
        }
        this.updateByPrimaryKeySelective(monthSupplytaskDtl4);
        return monthSupplytaskDtl4;
    }

}
